package softwaretest.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import softwaretest.Domain.User;
import softwaretest.dto.AuthResponse;
import softwaretest.repository.UserRepository;
import softwaretest.util.JwtUtil;

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwtUtil jwtUtil;

    // 用户注册
    public AuthResponse registerUser(User user) {
        if (userRepository.findByUsername(user.getUsername()) != null) {
            return new AuthResponse("Username already exists", null); // 用户名已存在
        }
        user.setPassword(passwordEncoder.encode(user.getPassword())); // 加密密码
        userRepository.save(user);
        return new AuthResponse("Registration successful", null); // 注册成功
    }

    // 用户登录
    public AuthResponse login(String username, String password) {
        User user = userRepository.findByUsername(username);
        if (user != null && passwordEncoder.matches(password, user.getPassword())) {
            String token = jwtUtil.generateToken(username);
            return new AuthResponse("Login successful", token); // 返回 Token
        }
        return new AuthResponse("Invalid credentials", null); // 验证失败
    }
}